<template>
  <div id="complex-content-to-pdf">
    <h1>复杂布局导出为PDF</h1>
    <div class="container">
      <div class="box" v-for="n in 5" :key="n" :style="{ backgroundColor: getRandomColor() }"></div>
    </div>
    <button @click="generatePDF">导出为PDF</button>
  </div>
</template>
<script>
import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';

export default {
  methods: {
    getRandomColor() {
      return '#' + Math.floor(Math.random() * 16777215).toString(16);
    },
    async generatePDF() {
      const element = document.getElementById('complex-content-to-pdf');
      const canvas = await html2canvas(element, { scale: 2 });
      const imgData = canvas.toDataURL('image/png');
      const pdf = new jsPDF();
      pdf.addImage(imgData, 'PNG', 0, 0, 210, 297);
      pdf.save('complex-layouot.pdf')
    }
  }
}
</script>
<style scoped>
.container {
  display: flex;
  flex-wrap: wrap;
}

.box {
  width: 100px;
  height: 100px;
  margin: 5px;
}
</style>